'use strict';
const db = uniCloud.database()
exports.main = async (event, context) => {
	try {
		const collection = db.collection(
			'userInfo'); // 替换为你的集合名称	
		const {
			nickName,
			avatar,
			gender = '1',
			openid
		} = event

		const isHave = await collection.where({
			openid
		}).get()
		if (isHave.data.length > 0) {
			return {
				code: 200,
				data: isHave.data[0]
			}
		}

		const dataInfo = {
			nickName,
			avatarUrl: avatar,
			gender,
			openid,
			createTime: new Date().getTime()
		}
		const result = await collection.add(dataInfo)
		const userInfo = {
			...dataInfo,
			_id: result.id
		}
		//返回数据给客户端
		return {
			code: 200,
			data: userInfo
		}

	} catch (e) {
		return {
			code: 500,
			data: e
		}
		//TODO handle the exception
	}

};